package com.tcr.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.tcr.common.TcProject;

public class ProjectDao {

	@SuppressWarnings("finally")
	public static List<TcProject> getAllPrjs() {
		Connection conn = null;
		List<TcProject> prjs = new ArrayList<TcProject>();
		try {
			conn = dbutil.pool.getConnection();
			PreparedStatement ps = conn
					.prepareStatement(SqlString.get_all_projects);
			ResultSet res = ps.executeQuery();
			while (res.next()) {
				int pid = res.getInt(1);
				String p_name = res.getString(2);
				int p_code = res.getInt(3);
				String p_svn = res.getString(4);

				prjs.add(new TcProject(pid, p_name, p_code, p_svn));
			}
		} catch (Exception ex) {
			logger.error(ex);
		} finally {
			if (conn != null)
				dbutil.pool.backConn(conn);
			return prjs;
		}
	}

	@SuppressWarnings("finally")
	public static boolean addProj(String p_name, int p_code, String p_svn) {
		Connection conn = null;
		boolean b = false;
		try {
			conn = dbutil.pool.getConnection();
			PreparedStatement ps = conn.prepareStatement(SqlString.add_proj);
			ps.setString(1, p_name);
			ps.setInt(2, p_code);
			ps.setString(3, p_svn);
			int res = ps.executeUpdate();

			b = (res != 0);
		} catch (Exception ex) {
			logger.error(ex);
		} finally {
			if (conn != null)
				dbutil.pool.backConn(conn);
			return b;
		}
	}

	@SuppressWarnings("finally")
	public static boolean delProj(int pid) {
		Connection conn = null;
		boolean b = false;
		try {
			conn = dbutil.pool.getConnection();
			PreparedStatement ps = conn.prepareStatement(SqlString.del_proj);
			ps.setInt(1, pid);

			int res = ps.executeUpdate();
			b = (res != 0);
		} catch (Exception ex) {
			logger.error(ex);
		} finally {
			if (conn != null)
				dbutil.pool.backConn(conn);
			return b;
		}
	}

	private final static DbUtil dbutil = DbUtil.getInstance();
	private final static Logger logger = Logger.getLogger(ProjectDao.class);

}
